package com.example.mykotilin.livedata

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.*

class DefaultDataSource(private val ioDispatcher: CoroutineDispatcher) : DataSource {

    //获取当前时间
    override fun getCurrentTime(): LiveData<Long> =
        liveData {
            while (true) {
                emit(System.currentTimeMillis()) //产生当前时间
                delay(1000) //每一秒出一次
            }
        }


    //每间隔两秒随机生成一个天气
    private val weatherConditions = listOf("Sunny", "Cloudy", "Rainy", "Stormy", "Snowy")
    override fun fetchWeather(): LiveData<String> = liveData {
        var counter = 0
        while (true) {
            counter++
            delay(2000)
            emit(weatherConditions[counter % weatherConditions.size])
        }
    }

    private val _cachedData = MutableLiveData("This is old data")
    override val cachedData: LiveData<String> = _cachedData
    //模拟网络请求
    override suspend fun fetchNewData() {
        withContext(Dispatchers.Main) {
            _cachedData.value = "Fetching new Data"
            _cachedData.value = simulateNetworkDataFetch()
        }
    }

    private var counter = 0
    private suspend fun simulateNetworkDataFetch(): String = withContext(ioDispatcher) {
        delay(3000)
        counter++
        "New data from request #$counter"
    }

}

interface DataSource {
    fun getCurrentTime(): LiveData<Long>;
    fun fetchWeather(): LiveData<String>;
    val cachedData: LiveData<String>
    suspend fun fetchNewData()
}